package cn.com.anypay.manager.common.utils;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * 支付宝签名工具类
 */
public class AlipaySignUtil {

    /**
     * 生成支付宝签名
     * @param params 请求参数
     * @param privateKey 私钥
     * @return 签名结果
     */
    public static String generateSign(Map<String, String> params, String privateKey) throws Exception {
        // 1. 参数排序
        Map<String, String> sortedParams = new TreeMap<>(params);
        sortedParams.remove("sign"); // 移除sign参数

        // 2. 拼接参数
        String signStr = sortedParams.entrySet().stream()
            .map(entry -> entry.getKey() + "=" + entry.getValue())
            .collect(Collectors.joining("&"));

        // 3. 读取私钥
        String privateKeyStr = privateKey.replace("-----BEGIN PRIVATE KEY-----", "")
                             .replace("-----END PRIVATE KEY-----", "")
                             .replaceAll("\\s+", "");

        // 4. 生成签名
        java.security.KeyFactory keyFactory = java.security.KeyFactory.getInstance("RSA");
        java.security.spec.PKCS8EncodedKeySpec keySpec = new java.security.spec.PKCS8EncodedKeySpec(
            Base64.getDecoder().decode(privateKeyStr)
        );
        java.security.PrivateKey rsaPrivateKey = keyFactory.generatePrivate(keySpec);

        java.security.Signature signature = java.security.Signature.getInstance("SHA256withRSA");
        signature.initSign(rsaPrivateKey);
        signature.update(signStr.getBytes(StandardCharsets.UTF_8));

        return Base64.getEncoder().encodeToString(signature.sign());
    }
}